<template>
  <div class="table-box">
    <div class="card table-search" style="padding: 15px 0 0 10px">
      <el-form :inline="true" :model="formModel" ref="searchFormRef">
        <el-form-item label="菜单名称:">
          <el-input v-model="formModel.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="菜单路径:">
          <el-input v-model="formModel.path" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <div>
            <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
            <el-button :icon="Delete" @click="reset(searchFormRef)">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <ProTable
      ref="proTable"
      title="菜单列表"
      row-key="path"
      :indent="20"
      :columns="columns"
      :request-api="getMenuList"
      :pagination="false"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="addMenu">新增菜单</el-button>
      </template>
      <!-- 菜单图标 -->
      <template #icon="scope">
        <!-- <el-icon :size="18">
          <component :is="scope.row.meta.icon"></component>
        </el-icon> -->
        <!-- <i :class="scope.row.meta.icon" class="iconfont2"> </i> -->
        <IconRenderer :icon="scope.row.meta.icon" />
      </template>
      <!-- 菜单状态 -->
      <template #MNU_Enabled="scope">
        <el-switch disabled v-model="scope.row.MNU_Enabled" class="ml-2 custom-switch" />
      </template>
      <!-- 菜单操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="Edit(scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteMenu(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <!-- 新增弹框 -->
    <el-dialog v-model="dialogSetting.visible" :title="dialogSetting.title" width="25%" draggable>
      <el-form label-width="90px" :model="formData" :rules="rules" ref="formRef">
        <el-form-item label="顺序号" prop="MNU_Index">
          <el-input v-model="formData.MNU_Index" />
        </el-form-item>
        <el-form-item label="菜单名称" prop="meta.title">
          <el-input v-model="formData.meta.title" />
        </el-form-item>
        <el-form-item label="菜单别名" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="重定向" prop="redirect">
          <el-input v-model="formData.redirect" />
        </el-form-item>
        <el-form-item label="菜单路径" prop="path">
          <el-input v-model="formData.path" />
        </el-form-item>
        <el-form-item label="父级菜单" prop="MNU_Parent">
          <el-tree-select
            clearable
            style="width: 100%"
            check-strictly
            v-model="formData.MNU_Parent"
            node-key="MNU_ID"
            :props="{ label: 'MNU_Title', children: 'children' }"
            :data="treeData"
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="formData.component" />
        </el-form-item>
        <el-form-item label="菜单图标" prop="meta.icon">
          <!-- <SelectIcon v-model:icon-value="formData.meta.icon" v-model="formData.meta.icon" /> -->
          <IconSelect v-model="formData.meta.icon" />
        </el-form-item>
        <el-form-item label="链接地址" prop="meta.isLink">
          <el-input v-model="formData.meta.isLink" />
        </el-form-item>
        <el-row>
          <el-col :span="5">
            <el-form-item label-width="60px" label="启用" prop="MNU_Enabled">
              <el-checkbox v-model="formData.MNU_Enabled" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label-width="60px" label="全屏" prop="meta.isFull">
              <el-checkbox v-model="formData.meta.isFull" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label-width="60px" label="隐藏" prop="meta.isHide">
              <el-checkbox v-model="formData.meta.isHide" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label-width="60px" label="固定" prop="meta.isAffix">
              <el-checkbox v-model="formData.meta.isAffix" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="60px" label="缓存" prop="meta.isKeepAlive">
              <el-checkbox v-model="formData.meta.isKeepAlive" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogSetting.visible = false">取消</el-button>
          <el-button type="primary" @click="handle"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="menuMange">
import { ref, reactive, onMounted, nextTick, toRefs } from "vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { Delete, EditPen, CirclePlus, Search } from "@element-plus/icons-vue";
// import SelectIcon from "@/components/SelectIcon/index.vue";
import IconSelect from "@/components/IconSelect/index.vue";
import IconRenderer from "@/layouts/components/Menu/IconRenderer.vue";
import ProTable from "@/components/ProTable/index.vue";
import type { FormInstance, FormRules } from "element-plus";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { getMenuList } from "@/api/modules/login";

const proTable = ref();
const { proxy } = useCurrentInstance();
// 搜索表单实例
const searchFormRef = ref<FormInstance>();
// 搜索表单绑定字段
const formModel = ref({
  name: "",
  path: ""
});
// 表格配置项
const columns: ColumnProps[] = [
  { prop: "MNU_Index", label: "序号", width: 80 },
  { prop: "meta.title", label: "菜单名称", align: "left" },
  { prop: "name", label: "菜单别名", align: "left" },
  { prop: "meta.icon", label: "菜单图标" },
  { prop: "path", label: "路径", width: 300 },
  { prop: "MNU_Enabled", label: "状态" },
  { prop: "component", label: "组件所在位置", width: 300 },
  { prop: "redirect", label: "路由重定向", width: 300 },
  { prop: "operation", label: "操作", width: 250, fixed: "right" }
];
// 点击表格保存当前行
const rowClick = ref();
// 菜单弹出框配置
const dialogSetting = reactive({
  visible: false,
  title: ""
});
// 菜单表单绑定字段
let formData = ref({
  MNU_Index: null,
  MNU_Parent: null,
  path: "",
  MNU_Enabled: true,
  component: "",
  name: "",
  meta: {
    icon: "",
    isAffix: false,
    isFull: false,
    isHide: false,
    isKeepAlive: false,
    isLink: "",
    title: ""
  },
  redirect: ""
});
// 菜单表单实例
const formRef = ref<FormInstance>();

// 菜单表单规则
const rules = reactive<FormRules>({
  "meta.title": [{ required: true, message: "请填写菜单名称", trigger: "blur" }],
  path: [{ required: true, message: "请填写路径", trigger: "blur" }]
});
// 父级菜单数据
const treeData = ref<any[]>([]);
const getTreeData = async () => {
  await proxy.$vueAxios.get("SysBaseTree/GetMenusTree").then((res: any) => {
    treeData.value = res.List;
  });
};
// 新增菜单
const addMenu = () => {
  dialogSetting.visible = true;
  dialogSetting.title = "新增";
  formRef.value?.resetFields();
};
// 编辑菜单
const Edit = (row: any) => {
  dialogSetting.visible = true;
  dialogSetting.title = "修改";
  rowClick.value = row;
  nextTick(() => {
    formData.value = Object.assign({}, row);
  });
};
// 确定事件
const handle = () => {
  formRef.value?.validate(valid => {
    if (valid) {
      if (dialogSetting.title === "新增") {
        const params = {
          mnU_ID: proxy.$global.createID(),
          mnU_Parent: formData.value.MNU_Parent,
          mnU_Index: formData.value.MNU_Index,
          mnU_Path: formData.value.path,
          mnU_Name: formData.value.name,
          mnU_Component: formData.value.component,
          mnU_Title: formData.value.meta.title,
          mnU_Icon: formData.value.meta.icon,
          mnU_Enabled: formData.value.MNU_Enabled,
          mnU_Enable_Joint_Authentication: true,
          mnU_IsFull: formData.value.meta.isFull,
          mnU_IsHide: formData.value.meta.isHide,
          mnU_IsLink: formData.value.meta.isLink,
          mnU_IsAffix: formData.value.meta.isAffix,
          mnU_IsKeepAlive: formData.value.meta.isKeepAlive,
          mnU_Is_Super: true,
          mnU_Create_By: 0,
          mnU_Create_Time: "",
          mnU_Remark: "",
          mnU_Type: "",
          mnU_Redirect: formData.value.redirect
        };
        proxy.$vueAxios.post("Master_Base_Menus", params).then(() => {
          proTable.value.getTableList();
          getTreeData();
          dialogSetting.visible = false;
        });
      } else {
        const params = {
          mnU_ID: rowClick.value.MNU_ID,
          mnU_Parent: formData.value.MNU_Parent,
          mnU_Index: formData.value.MNU_Index,
          mnU_Path: formData.value.path,
          mnU_Name: formData.value.name,
          mnU_Component: formData.value.component,
          mnU_Title: formData.value.meta.title,
          mnU_Icon: formData.value.meta.icon,
          mnU_Enabled: formData.value.MNU_Enabled,
          mnU_Enable_Joint_Authentication: true,
          mnU_IsFull: formData.value.meta.isFull,
          mnU_IsHide: formData.value.meta.isHide,
          mnU_IsLink: formData.value.meta.isLink,
          mnU_IsAffix: formData.value.meta.isAffix,
          mnU_IsKeepAlive: formData.value.meta.isKeepAlive,
          mnU_Is_Super: true,
          mnU_Create_By: 0,
          mnU_Create_Time: "",
          mnU_Remark: "",
          mnU_Type: "",
          mnU_Redirect: formData.value.redirect
        };
        proxy.$vueAxios.put("Master_Base_Menus", params).then(() => {
          proTable.value.getTableList();
          getTreeData();
          dialogSetting.visible = false;
        });
      }
    }
  });
};
// 删除菜单（示例、根据自己后端接口来）
const deleteMenu = async (params: any) => {
  proxy.$messageBox
    .confirm("确定删除该数据？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      proxy.$vueAxios.post("Master_Base_Menus/Delete", [params.MNU_ID]).then((res: any) => {
        if (res.Mark) {
          proTable.value.getTableList();
          getTreeData();
          proxy.$message.success("删除成功");
        } else {
          proxy.$message.error("删除失败");
        }
      });
    })
    .catch(() => {
      proxy.$message.warning("取消删除");
    });
};
// 查询菜单
const search = () => {
  proTable.value.tableData = recursion(treeData.value);
};
// 递归
const recursion = (tree: any[]) => {
  if (!tree) return;
  const result: any[] = [];
  tree.forEach(item => {
    if (item.MNU_Title.includes(formModel.value.name) && item.path.toLowerCase().includes(formModel.value.path.toLowerCase())) {
      result.push(item);
      return;
    }
    const children = recursion(item.children);
    if (children && children.length > 0) {
      result.push({ ...item, children });
    }
  });
  return result;
};
// 重置搜索框
const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
onMounted(() => {
  getTreeData();
});
</script>

<style lang="scss" scoped>
.custom-switch {
  --el-switch-on-color: #13ce66;
  --el-switch-off-color: #ff4949;
}
</style>
